package com.baike.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.baike.data.Result;
import com.baike.em.ConstantEnum;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("load")
@RefreshScope
public class UploadDownloadUtil {

    //图片下载
    @RequestMapping("downloadFile")
    public void downloadFile(String filename, HttpServletResponse resp) throws IOException {
        File file = new File("D:\\products\\"+filename);
        FileInputStream fis = new FileInputStream(file);
        resp.setHeader("Content-Disposition", "attachment;filename="+ filename);
        ServletOutputStream os = resp.getOutputStream();
        byte[] arr = new byte[1024];
        int b;
        while((b=fis.read(arr)) != -1) {
            os.write(arr);
        }
        os.close();
        fis.close();
    }

    //上传1
    @RequestMapping("uploadFiles")
    @ResponseBody
    public static Map<String, Object> uploadFiles(MultipartFile myFile) {
        //上传地址
        String path="D:\\products\\img\\product\\insert\\";
        String filename = myFile.getOriginalFilename();
        try {
            File file = new File(path + filename);
            myFile.transferTo(file);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("fileuploaded","img/product/insert/"+filename);
        return map;
    }

    //图片上传
    @RequestMapping("upload")
    @ResponseBody
    public static Result upload(@RequestParam("image") MultipartFile image){
        try {
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String http = "https://";
            String endpoint = "oss-cn-beijing.aliyuncs.com";
            String buketName = "tang-cool";


            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = "LTAI5t5pbcaeCUgLSGuGgFdS";
            String accessKeySecret = "tPQ1JPyYuPQPYLzllAEx7Cl5j534Pb";

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 填写字符串。
            String content = "Hello OSS";
            //
            InputStream inputStream = image.getInputStream();
            String filename = image.getOriginalFilename();
            String key = "image/"+filename;
            // 创建PutObjectRequest对象。
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            PutObjectRequest putObjectRequest = new PutObjectRequest(buketName,key,inputStream);

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            ossClient.putObject(putObjectRequest);

            // 关闭OSSClient。
            ossClient.shutdown();
            return Result.build(ConstantEnum.SUCCESS).setResult(http+buketName+"."+endpoint+"/"+key);
        }catch (Exception e){
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR);
        }
    }
}
